package com.vf.admin.client.controller.pay.sandpay;

import com.alibaba.fastjson.JSONArray;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.PaySelectDao;
import com.vf.admin.client.service.PaySelectService;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.PaySelect;
import com.vf.admin.miaodong.entity.WechatPayConfigs;
import com.vf.admin.utils.douyin.PageReader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * <p>Title : </p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows11</p>
 *
 * @Author : zxw
 * @Date 2023/9/25 20:17
 */
@Service
public class SandpayService {


    @Resource
    private PaySelectDao paySelectDao;
    @Resource
    private RedisUtil redisUtil;

    public PaySelect getPaySelect() {
        List<PaySelect> paySelects = null;
        if (!redisUtil.hasKey(RedisKeys.PAYSELECT)) {
            paySelects = paySelectDao.list();
            redisUtil.set(RedisKeys.PAYSELECT, paySelects, RedisKeys.ALICONFIGSOUTTIME);
        } else {
            paySelects = (List<PaySelect>) redisUtil.get(RedisKeys.PAYSELECT);
        }
        Integer sumWeight = 0;//总权重的值
        JSONArray as = new JSONArray();//存入对象用于概率
        Integer index = 0;
        for (int i = 0; i < paySelects.size(); i++) {
            Integer weight = paySelects.get(i).getWeight();
            if (weight > 0) {
                sumWeight = sumWeight + weight;
                for (int j = 0; j < weight; j++) {
                    as.add(index, paySelects.get(i));
                    index++;//放后面保证0也有值
                }
            }
        }
        Integer r = new Random().nextInt(sumWeight + 1);//随机数生成概率
        PaySelect paySelect1 = (PaySelect) as.get(r);
        System.out.println("权重：" + paySelect1);
        return (PaySelect) as.get(r);
    }

}
